package spring.chatroom.java_chatroom.controller;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import spring.chatroom.java_chatroom.common.constant.Constants;
import spring.chatroom.java_chatroom.common.constant.VerifyHtml;
import spring.chatroom.java_chatroom.common.utils.MailUtil;
import spring.chatroom.java_chatroom.common.utils.RedisUtil;
import spring.chatroom.java_chatroom.controller.pojo.EmailCode;
import spring.chatroom.java_chatroom.mapper.UserMapper;
import spring.chatroom.java_chatroom.pojo.response.Response;

import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("verify")
public class VerifyCodeController {

    @Autowired
    MailUtil mailUtil;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    UserMapper userMapper;

    @RequestMapping("getEmailCode")
    public Response getEmailCode(@NotNull @RequestBody EmailCode emailCode) {
        log.info("收到生成验证码请求 {}", emailCode);


        StringBuilder code1 = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code1.append(random.nextInt(10));
        }

        String code = code1.toString();

        log.info("验证码 {}", code);

        //发送给邮箱
        String state = mailUtil.sendHtmlMail(emailCode.getEmail(), Constants.title, VerifyHtml.setBindHtml(emailCode.getUserName(), code));

        if(state != null) {
            return Response.success(Map.of("status", "fail", "msg", state));
        }

        //储存到redis中 5分钟过期
        state = redisUtil.set(emailCode.getEmail(), code, 300L);

        if(state != null) {
            return Response.success(Map.of("status", "fail", "msg", state));
        }

        return Response.success(Map.of("status", "success", "code", code));
    }

    private boolean verifyIdEmail(Integer userId, String email) {
        return userMapper.getUserByUserIdAndEmail(userId, email) != null;
    }
}
